package common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class FileUtil {
    public static void examplePaths() {
        File file1 = new File("");
        System.out.println(file1.getAbsolutePath());
        File file2 = new File("/");
        System.out.println(file2.getAbsolutePath());
    }

    public static void makeDirs(String path) {
        File file = new File(path);
        LogUtil.info("try to create folder for file: " + path);
        new File(file.getParent()).mkdirs();
    }

    public static void createFolder(String path) {
        makeDirs(path);
    }

    public static void save(String path, InputStream inputStream) throws Exception {
        createFolder(path);
        FileOutputStream fileWriter = new FileOutputStream(path);
        int b;
        while ((b = inputStream.read()) != -1)
            fileWriter.write(b);
        inputStream.close();
        fileWriter.close();
    }

    public static void write(String path, String value) {
        try {
            createFolder(path);
            FileOutputStream fileWriter = new FileOutputStream(path);
            fileWriter.write(value.getBytes());
            fileWriter.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void create(String path, String value) {
        write(path, value);
    }

    public static void save(String path, String value) {
        write(path, value);
    }

    public static String getText(String path) throws Exception {
        return BinaryUtil.getText(new FileInputStream(path));
    }

    public static boolean Exist(String path) {
        return new File(path).exists();
    }

    public static void appendText(String path, String value) throws Exception {
        createFolder(path);
        LogUtil.info("try to append to file {} with value of length {}", path, value.length());
        FileOutputStream writer = new FileOutputStream(path, true);
        ByteBuffer buffer = BinaryUtil.GetBufferFromText(value);
        writer.write(buffer.array(), 0, buffer.limit());
        writer.close();
    }

    public static void appendLine(String path, String value) throws Exception {
        appendText(path, value + StringUtil.crlf);
    }
}
